
#include "stdafx.h"
#include "dmerrorhandling.h"

HRESULT		DMHRESULTFromServerError( PluginAlgorithms::DMEngineException^ dmex)
{
	return dmex->Result;
}

HRESULT		DMHRESULTFromAlgorithmError( System::Exception^ pex)
{
	CComPtr<ICreateErrorInfo> spCErrInfo;
	HRESULT hr;
	hr = CreateErrorInfo(&spCErrInfo);
	if( FAILED(hr) )
		return hr;

	try
	{
		// Serialize the lowest level exception
		while( pex->InnerException != nullptr )
		{
			pex = pex->InnerException;
		}


		if( pex->Message != nullptr )
		{
			BSTR bstrTmp = (BSTR)(void*)System::Runtime::InteropServices::Marshal::StringToBSTR( pex->Message );
			spCErrInfo->SetDescription(bstrTmp);
			System::Runtime::InteropServices::Marshal::FreeBSTR((IntPtr)(void*)bstrTmp);
		}

		if( pex->Source != nullptr )
		{
			BSTR bstrTmp = (BSTR)(void*)System::Runtime::InteropServices::Marshal::StringToBSTR( pex->Source );
			spCErrInfo->SetSource(bstrTmp);
			System::Runtime::InteropServices::Marshal::FreeBSTR((IntPtr)(void*)bstrTmp);
		}

		if( pex->HelpLink != nullptr )
		{
			BSTR bstrTmp = (BSTR)(void*)System::Runtime::InteropServices::Marshal::StringToBSTR( pex->HelpLink );
			spCErrInfo->SetHelpFile(bstrTmp);
			System::Runtime::InteropServices::Marshal::FreeBSTR((IntPtr)(void*)bstrTmp);
		}

		CComPtr<IErrorInfo> spErrInfo;
		hr = spCErrInfo->QueryInterface(IID_IErrorInfo, (LPVOID FAR*) &spErrInfo);
		if (SUCCEEDED(hr))
		{
			SetErrorInfo(0, spErrInfo);
		}

	}
	catch(...)
	{
		// nothing to do, error while raising error
	}
	return E_FAIL;
}
